import { clsx, type ClassValue } from "clsx"
import { twMerge } from "tailwind-merge"

export function cn(...inputs: ClassValue[]) {
  return twMerge(clsx(inputs))
}

// 格式化日期为苹果风格显示
export function formatAppleDate(date: Date): string {
  return date.toLocaleDateString('zh-CN', {
    weekday: 'long',
    month: 'long',
    day: 'numeric'
  });
}

// 格式化时间为苹果风格显示
export function formatAppleTime(date: Date): string {
  return date.toLocaleTimeString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit'
  });
}

// 生成随机颜色用于应用图标背景
export function getRandomAppColor(): string {
  const colors = [
    'bg-red-500', 'bg-orange-500', 'bg-yellow-500', 'bg-green-500', 
    'bg-blue-500', 'bg-indigo-500', 'bg-purple-500', 'bg-pink-500'
  ];
  return colors[Math.floor(Math.random() * colors.length)];
}

// 图片处理工具函数
export function fileToBase64(file: File): Promise<string> {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = () => resolve(reader.result as string);
    reader.onerror = reject;
    reader.readAsDataURL(file);
  });
}

// 背景图片相关本地存储操作
export const BackgroundStorage = {
  get: (): string | null => {
    return localStorage.getItem('customBackground');
  },
  
  set: (imageData: string): void => {
    localStorage.setItem('customBackground', imageData);
  },
  
  remove: (): void => {
    localStorage.removeItem('customBackground');
  }
};

import axios from 'axios';

// 默认壁纸作为备用方案
const DEFAULT_WALLPAPERS = [
  'https://space.coze.cn/api/coze_space/gen_image?image_size=landscape_16_9&prompt=beautiful%20mountain%20landscape%2C%20sunset%2C%20nature%2C%204k%20photography&sign=6ececa3f1aecfd0f6807164de1cfaf7a',
  'https://space.coze.cn/api/coze_space/gen_image?image_size=landscape_16_9&prompt=ocean%20sunset%2C%20seaside%2C%20calm%2C%204k%20photography&sign=a2870b587ae0cc88fb4a59dad2bc593e',
  'https://space.coze.cn/api/coze_space/gen_image?image_size=landscape_16_9&prompt=forest%20path%2C%20morning%20mist%2C%20green%20trees%2C%204k%20photography&sign=a021b60cf58ab396aeef8ae75d04c527',
  'https://space.coze.cn/api/coze_space/gen_image?image_size=landscape_16_9&prompt=starry%20night%2C%20milky%20way%2C%20mountains%2C%204k%20photography&sign=bd50c7e681cb2ca0e4e95551717ed8b1',
];

// 获取Bing壁纸图片，带重试机制和备用方案
export const fetchBingWallpapers = async (retries = 3, delay = 1000): Promise<string[]> => {
  try {
    const response = await axios.get(
      'http://web.kkdaly.top/bing_api/HPImageArchive.aspx?format=js&idx=0&n=10',
      {
        timeout: 2000, headers: {
          "Access-Control-Allow-Origin": "*",
          "Access-Control-Allow-Methods": "GET, POST, OPTIONS, PUT, DELETE",
          "Access-Control-Allow-Headers": "Content-Type, Authorization, X-Requested-With",
          "Access-Control-Allow-Credentials":"true"
      } } // 5秒超时
    );
    
    if (response.data.images && Array.isArray(response.data.images) && response.data.images.length > 0) {
      return response.data.images.map(img => `http://web.kkdaly.top/bing_img/${img.url}`);
    }
    
    console.warn('Bing API返回空数据，使用默认壁纸');
    return [...DEFAULT_WALLPAPERS];
  } catch (error) {
    console.error(`获取Bing壁纸失败(剩余重试次数: ${retries})`, error);
    
    // 如果还有重试次数，等待后重试
    if (retries > 0) {
      await new Promise(resolve => setTimeout(resolve, delay));
      return fetchBingWallpapers(retries - 1, delay * 2); // 指数退避策略
    }
    
    // 所有重试都失败，使用默认壁纸
    console.error('所有重试均失败，使用默认壁纸');
    return [...DEFAULT_WALLPAPERS];
  }
};

// 网站相关本地存储操作
export const WebsiteStorage = {
  get: (): Array<{id: number, name: string, icon: string, url: string}> => {
    const websites = localStorage.getItem('websites');
    if (websites) {
      return JSON.parse(websites);
    }
    // 默认网站数据
    const defaultWebsites:any[] = [];
    WebsiteStorage.set(defaultWebsites);
    return defaultWebsites;
  },
  
  set: (websites: Array<{id: number, name: string, icon: string, url: string}>): void => {
    localStorage.setItem('websites', JSON.stringify(websites));
  },
  
  add: (website: {name: string, icon: string, url: string}): void => {
    const websites = WebsiteStorage.get();
    const newId = websites.length > 0 ? Math.max(...websites.map(w => w.id)) + 1 : 1;
    websites.push({ ...website, id: newId });
    WebsiteStorage.set(websites);
  },
  
  update: (updatedWebsite: {id: number, name: string, icon: string, url: string}): void => {
    const websites = WebsiteStorage.get();
    const index = websites.findIndex(w => w.id === updatedWebsite.id);
    if (index !== -1) {
      websites[index] = updatedWebsite;
      WebsiteStorage.set(websites);
    }
  },
  
  remove: (id: number): void => {
    let websites = WebsiteStorage.get();
    websites = websites.filter(w => w.id !== id);
    WebsiteStorage.set(websites);
  }
};

// 节日相关本地存储操作
export const HolidayStorage = {
  get: (): Array<{date: string, name: string, isCustom: boolean}> => {
    const holidays = localStorage.getItem('holidays');
    if (holidays) {
      return JSON.parse(holidays);
    }
    // 默认节日数据
    const defaultHolidays = [
      { date: '01-01', name: '元旦', isCustom: false },
      { date: '02-10', name: '春节', isCustom: false },
      { date: '04-04', name: '清明节', isCustom: false },
      { date: '05-01', name: '劳动节', isCustom: false },
      { date: '06-10', name: '端午节', isCustom: false },
      { date: '09-15', name: '中秋节', isCustom: false },
      { date: '10-01', name: '国庆节', isCustom: false },
      { date: '12-25', name: '圣诞节', isCustom: false }
    ];
    HolidayStorage.set(defaultHolidays);
    return defaultHolidays;
  },
  
  set: (holidays: Array<{date: string, name: string, isCustom: boolean}>): void => {
    localStorage.setItem('holidays', JSON.stringify(holidays));
  },
  
  add: (holiday: {date: string, name: string}): void => {
    const holidays = HolidayStorage.get();
    // 检查是否已存在该日期的自定义节日
    const existingIndex = holidays.findIndex(h => 
      h.date === holiday.date && h.isCustom
    );
    
    if (existingIndex !== -1) {
      // 更新现有节日
      holidays[existingIndex] = { ...holiday, isCustom: true };
    } else {
      // 添加新节日
      holidays.push({ ...holiday, isCustom: true });
    }
    
    HolidayStorage.set(holidays);
  },
  
  remove: (date: string): void => {
    let holidays = HolidayStorage.get();
    holidays = holidays.filter(h => !(h.date === date && h.isCustom));
    HolidayStorage.set(holidays);
  },
  
  getByDate: (date: Date): string | null => {
    const holidays = HolidayStorage.get();
    const dateStr = `${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
    const holiday = holidays.find(h => h.date === dateStr);
    return holiday ? holiday.name : null;
  }
};

// 格式化日期为 MM-DD 格式
export function formatDateForHoliday(date: Date): string {
  return `${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
}

// 从URL获取网站favicon图标
export function getFaviconUrl(url: string): string {
  try {
    const parsedUrl = new URL(url);
    return `${parsedUrl.origin}/favicon.ico`;
  } catch (error) {
    return '';
  }
}